<?php

namespace cms\modules\v1\controllers;

use cms\modules\common\controllers\DefaultController;
use cms\modules\v1\models\admin\Admin;
use cms\modules\v1\models\Captcha;
use common\models\CacheKeys;
use common\models\Functions;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use yii\redis\Cache;
use yii\web\IdentityInterface;
use yii\filters\auth\HttpHeaderAuth;
use yii\web\Response;

/**
 * Default controller for the `v1` module
 */
class LoginController extends DefaultController
{

    public $modelClass = 'cms\modules\v1\models\Admin';

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'authenticator' => [
                'class' =>  HttpHeaderAuth::className(),    //head头部验证
                'header' => 'access-token',
                'optional' => [
                    'in', 'out','captcha'
                ]
            ]
        ]);
    }

    /**
     * [ 验证码 ]
     * @return [type] [description]
     */
    public function actionCaptcha()
    {
        if (Yii::$app->request->isGet) {
            return (new Captcha())->create();
        }
    }


    /**
     * 用户 - 用户登录
     * @return array
     */
    public function actionIn() {
        $model = new Admin();
        $model->setScenario('login');
        $ip = Functions::getRemoteIp();
//        $post = Yii::$app->request->post();
//        $login = $post["login_name"];
//        $pass = $post["password"];
//
//        if (strlen($login) > 12) {
//            return Functions::formatRestAPI(1, '账号密码错误');
//        }
//        if (strlen($pass) > 18) {
//            throw new Exception('密码最多18位');
//        }

        CacheKeys::checkFrequency("bg_" . $ip, 5);

        if ($model->load(Yii::$app->request->post(),'')) {
            $user = $model->login();
            try {
                if (!$user) {
                    $key = key($model->errors);
                    $msg = $key ? $model->errors[$key][0] : "登录失败";
                    throw new Exception($msg, 1);
                }
                if (!($user instanceof IdentityInterface)) {
                    throw new Exception($user->errors, 1);
                }

//                if ($user['is_mfa'] == Status::COMMON_RADIO_YES) {
//                    $code = Yii::$app->request->post("code");
//                    $sec = $user['mfa_sec'];
//                    if (empty($code)) {
//                        throw new Exception('请输入动态口令');
//                    }
//
//                    //对用户输入的6位动态码进行校验，参数$sec是与此用户关联的秘钥
//                    $obj = new GoogleAuthenticator();
//                    $ret = $obj->verifyCode($sec, $code);
//
//                    if (!$ret) {
//                        throw new Exception('动态口令校验失败');
//                    }
//                }

                $data['loginName'] = $user->login_name;
                $data['access_token'] = $user->access_token;
                $data['nick_name'] = $user->nick_name;
                $data['id'] = $user->id;

                return Functions::formatRestAPI(0, "登录成功", $data);

            } catch (Exception $e) {
                $code = $e->getCode() ? $e->getCode() : 1;
                return Functions::formatRestAPI($code, $e->getMessage());
            }
        }
        return Functions::formatRestAPI(1, '数据有误');
    }

    /**
     * 用户 - 用户登出
     * @return array
     */
    public function actionOut() {
        if (Yii::$app->request->isPost) {
            return (new Admin())->doLogout();
        }
    }

}
